package com.aop.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author xinwang
 * @date 2020/2/24 10:51
 **/
@Aspect
@Component
public class AopTransaction {
    //spring 声明式事务
    @Autowired
    private TransactionUtils transactionUtils;

    @Pointcut("execution(* com.aop.service.UserService.* (..))")
    public void pointcut() {

    }

    @Around("pointcut()")
    public void around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("环绕通知 开启事务");
        //开启事务
        TransactionStatus begin  = transactionUtils.begin();
        //执行代理目标方法
        point.proceed();
        //提交事务
        transactionUtils.commit(begin);
        System.out.println("环绕通知 提交事务");
    }

    @AfterThrowing("pointcut()")
    public  void afterThrowing(){
        System.out.println("异常通知");
        //回滚事务
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
